package com.zrrd.yunchmall.order.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zrrd.yunchmall.order.client.ProductServiceClient;
import com.zrrd.yunchmall.order.entity.Order;
import com.zrrd.yunchmall.order.entity.OrderItem;
import com.zrrd.yunchmall.order.entity.OrderOperateHistory;
import com.zrrd.yunchmall.order.mapper.OrderMapper;
import com.zrrd.yunchmall.order.mapper.OrderOperateHistoryMapper;
import com.zrrd.yunchmall.order.service.IOrderItemService;
import com.zrrd.yunchmall.order.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.yunchmall.product.entity.Product;
import com.zrrd.yunchmall.user.entity.Admin;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author LiYe
 * @since 2024-01-15
 */
@Service
@SuppressWarnings("all")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    // 注入一个商品服务的客户端实例，便于远程调用商品服务的接口
    @Autowired
    private ProductServiceClient productServiceClient;
    @Autowired
    private OrderOperateHistoryMapper historyMapper;
    @Autowired
    private IOrderItemService orderItemService;

    @Override
//    @Transactional //本地事务注解
    @GlobalTransactional //Seata框架用于全局事务处理的注解
    public void submitOrder(Integer pid, Integer num, Integer memberId, String memberUsername, String receiverName, String receiverPhone) {
        //先查询商品信息
        Product product = productServiceClient.detail(pid).getData();
        //判断库存是否充足
        if (product.getStock() >= num) {
            //计算总价 = 商品单价 * 数量
            float totalAmount = product.getPrice().floatValue() * num;
            Order order = new Order();
            order.setMemberId((long) memberId.intValue());//设置会员id
            order.setMemberUsername(memberUsername);//设置会员名
            order.setCreateTime(LocalDateTime.now());//设置创建订单时间
            order.setReceiverName(receiverName);
            order.setReceiverPhone(receiverPhone);
            order.setTotalAmount(new BigDecimal(totalAmount));//设置订单总金额
            this.save(order);//保存订单
            //保存订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductPrice(product.getPrice());
            orderItem.setProductQuantity(num);
            orderItemService.save(orderItem);
            //远程调用商品服务，完成修改库存的操作
            productServiceClient.subStock(pid, num);
            System.out.println("下单成功~");
        } else {
            System.out.println("库存不足~");
        }
    }

    @Override
    // 只能用于管理本地事务，第3步需要跨服务完成，会产生分布式事务问题（找Seata帮忙）
    @Transactional
    // @GlobalTransational
    public void closeOrder(String ids, String note) {
        //1 修改订单状态
        List<Order> orderList = super.listByIds(Arrays.asList(ids.split(",")));
        orderList.forEach(order -> {
            order.setStatus(4);//将订单状态改成 4->已关闭
            //2 记录日志
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(order.getId());
            history.setOrderStatus(4);
            history.setNote(note);//设置备注
            history.setOperateMan("当前登录管理员");
            historyMapper.insert(history);//记录这次修改

            //3 释放库存（需要调用商品服务完成）
            List<Map<String, Object>> params = new LinkedList<>();
            QueryWrapper queryWrapper = new QueryWrapper();
            // select product_id as productId, product_sku_id as skuId, product_quantity as quantity
            // from oms_order_item
            // where order_id=?
            queryWrapper.eq("order_id", order.getId());
            queryWrapper.select("product_id as productId", "product_sku_id as skuId", "product_quantity as quantity");
            params = orderItemService.listMaps(queryWrapper);
            productServiceClient.freeStock(params);// 远程调用服务释放内存

            //4 是不是要归还优惠券
        });
        super.updateBatchById(orderList);//执行一个批量更新
    }

    @Override
    @Transactional
    public void delivery(List<Map<String, Object>> params) {
        //1 循环遍历集合
        params.forEach(item -> {
            //2 设置条件，执行update操作
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("id", item.get("orderId"));
            updateWrapper.set("status", 2);//将订单状态改成2->已返货
            updateWrapper.set("delivery_company", item.get("deliveryCompany"));//修改快递公司
            updateWrapper.set("delivery_sn", item.get("deliverySn"));//修改快递单号
            updateWrapper.set("delivery_time", LocalDateTime.now());//修改发货时间
            super.update(updateWrapper);
            //3 记录操作日志
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(Long.valueOf(item.get("orderId").toString()));
            history.setOrderStatus(2);
            history.setNote("订单发货");//设置备注
            history.setOperateMan("当前登录管理员");
            historyMapper.insert(history);//记录这次修改
        });
    }

    @Override
    @Transactional
    public void remove(String ids, Admin admin) {
        //1 遍历订单id
        for (String orderId : ids.split(",")) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.select("status");
            queryWrapper.eq("id", orderId);
            Order order = super.getOne(queryWrapper);
            // 订单id存在，且订单状态满足删除条件
            if (order != null && (order.getStatus() == 4 || order.getStatus() == 5)) {
                //2 删除满足条件的订单（状态为4和5的订单）
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.set("delete_status", 1);
                updateWrapper.eq("id", orderId);
                super.update(updateWrapper);
                //3 记录操作历史
                OrderOperateHistory history = new OrderOperateHistory();
                history.setOrderId(Long.valueOf(orderId));
                history.setOrderStatus(6);
                history.setNote("删除订单");//设置备注
                history.setOperateMan(admin.getId() + "," + admin.getUsername());
                historyMapper.insert(history);//记录这次修改
            }
        }
    }

    @Override
    @Transactional
    public void updateReceiverInfo(Map<String, Object> params) {
        //1 修改信息
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", params.get("orderId"));
        updateWrapper.set("receiver_name", params.get("receiverName"));
        updateWrapper.set("receiver_phone", params.get("receiverPhone"));
        updateWrapper.set("receiver_post_code", params.get("receiverPostCode"));
        updateWrapper.set("receiver_province", params.get("receiverProvince"));
        updateWrapper.set("receiver_city", params.get("receiverCity"));
        updateWrapper.set("receiver_region", params.get("receiverRegion"));
        updateWrapper.set("receiver_detail_address", params.get("receiverDetailAddress"));
        super.update(updateWrapper);
        //2 添加操作历史
        OrderOperateHistory history = new OrderOperateHistory();
        history.setOrderId(Long.valueOf(params.get("orderId").toString()));
        history.setOrderStatus(Integer.valueOf(params.get("status").toString()));
        history.setNote("修改收件人信息");//设置备注
        history.setOperateMan("登录人信息");
        historyMapper.insert(history);//记录这次修改
    }
/*
{
  "orderId": 13,
  "freightAmount": 0,
  "discountAmount": 50,
  "status": 0
}
 */
    @Override
    @Transactional
    public void updateMoneyInfo(Map<String, Object> params, Admin admin) {
        Order order = super.getById(Long.valueOf(params.get("orderId").toString()));
        float newfreightAmount = 0f;
        if (params.get("freightAmount") != null){
            //从参数中得到新的运费是多少
            newfreightAmount = Float.valueOf(params.get("freightAmount").toString());
        }
        float discountAmount = 0f;
        if (params.get("discountAmount") != null) {
            //从参数中得到新的折扣是多少
            discountAmount = Float.valueOf(params.get("discountAmount").toString());
        }
        order.setFreightAmount(BigDecimal.valueOf(newfreightAmount));
        order.setDiscountAmount(BigDecimal.valueOf(discountAmount));
        float totalAmount = order.getTotalAmount().floatValue();//商品合计
        float promotionAmount = order.getPromotionAmount().floatValue();//活动减免
        float integrationAmount = order.getIntegrationAmount().floatValue();//积分抵扣
        float couponAmount = order.getCouponAmount().floatValue();//优惠券抵扣
        /*
        实际支付金额（payAmount）=商品合计（totalAmount） + 运费（freightAmount）
                                - （活动减免）promotion_amount
                                - （折扣费用）discount_amount
                                - （积分抵扣）integration_amount
                                - （优惠券）coupon_amount
         */
        float payAmount = totalAmount + newfreightAmount
                        - promotionAmount
                        - discountAmount
                        - integrationAmount
                        - couponAmount;
        order.setPayAmount(BigDecimal.valueOf(payAmount));
        super.updateById(order);

        //2 添加操作历史
        OrderOperateHistory history = new OrderOperateHistory();
        history.setOrderId(order.getId());
        history.setOrderStatus(Integer.valueOf(params.get("status").toString()));
        history.setNote("修改费用信息");//设置备注
        history.setOperateMan(admin.getId() + "," + admin.getUsername());
        historyMapper.insert(history);//记录这次修改

    }
}
